import win32gui

class WindowManager:
    def __init__(self):
        self.windows = []
    
    def list_windows(self):
        """列出当前所有可见窗口"""
        self.windows = []
        
        def enum_windows_callback(hwnd, results):
            if win32gui.IsWindowVisible(hwnd):
                window_title = win32gui.GetWindowText(hwnd)
                if window_title:
                    results.append((hwnd, window_title))
        
        # 获取所有可见窗口
        win32gui.EnumWindows(enum_windows_callback, self.windows)
        
        # 按标题排序
        self.windows.sort(key=lambda x: x[1])
        
        return self.windows
    
    def get_window_info(self, index):
        """根据索引获取窗口信息"""
        if 0 <= index < len(self.windows):
            return self.windows[index]
        return None
    
    def get_window_rect(self, hwnd):
        """获取窗口位置和大小，并进行坐标验证，同时将窗口置于前台"""
        try:
            # 尝试将窗口置于前台，确保录制时窗口可见
            try:
                # 先最小化再还原，确保窗口状态正常
                win32gui.ShowWindow(hwnd, 9)  # SW_RESTORE = 9
                # 激活窗口并设置为前台窗口
                win32gui.SetForegroundWindow(hwnd)
                # 短暂延迟确保窗口已置于前台
                import time
                time.sleep(0.1)
            except Exception as fw_error:
                print(f"将窗口置于前台失败: {str(fw_error)}")
            
            # 获取窗口坐标和大小
            left, top, right, bottom = win32gui.GetWindowRect(hwnd)
            width = right - left
            height = bottom - top
            
            # 验证坐标和大小的有效性
            # 防止获取到异常的负坐标（如-21333等）或过小的窗口
            if left < -10000 or top < -10000 or width <= 0 or height <= 0 or width > 10000 or height > 10000:
                print(f"获取到无效的窗口坐标或大小: left={left}, top={top}, width={width}, height={height}")
                return 0, 0, 0, 0
                
            return left, top, width, height
        except Exception as e:
            print(f"获取窗口信息失败: {str(e)}")
            return 0, 0, 0, 0
    
    def get_window_list_for_display(self):
        """获取用于显示的窗口列表"""
        display_list = []
        for i, (hwnd, title) in enumerate(self.windows):
            display_list.append(f"{i+1}. {title}")
        return display_list